import axios from 'axios'
import {
  Message
} from 'element-ui'
import {
  getToken,
  getUserName
} from './auth'
import store from '@/store/index'
import {
  logout,
  getRealToken
} from './login'

// create an axios instance
const service = axios.create({
  baseURL: env.apiHost + ':' + env.apiPort, // api的base_url
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = getToken() || ''
    config.headers['factoryId'] = window.localStorage.getItem('factoryId') || ''
    config.headers['checkFactory'] = true
    config.headers['username'] = getUserName() || ''
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// respone interceptors
service.interceptors.response.use(
  response => {
    if (response === undefined) return

    const res = response.data
    if (res.code === 401) {
      // 如果请求时200但是内容为401说明 登出了需要强制退出
      store.dispatch('LogOut').then(() => {
        logout(location.href)
      })
      return
    }

    if (res.status === 200 ||
        res.code === 200 ||
        res.resultCode === 200) {
      if (res.message && res.message != '') {
        Message({
          type: 'success',
          message: res.message
        })
      }
      return res
    } else if (
      response.headers['content-disposition'] &&
      response.headers['content-disposition'].indexOf('filename') > 0) {
      return response
    } else {
      Message({
        message: res.message,
        type: 'error',
      })
      return Promise.reject('error')
    }
  },
  error => {
    if (error.response && error.response.data && error.response.data.status === 1) {
      return window.location.href = window.env.factoryHref
    }

    if (error.response && error.response.status === 401) {
      store.dispatch('LogOut').then(() => {
        logout(location.href)
      })
      return
    }

    if (!error.response || !error.response.config) {
      Message({
        message: '服务繁忙，请稍后刷新页面后重试!',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject('error')
    }
    // 请求接口错误回调
    Message({
      message: error.response.data.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error.response)
  }
)

export default service
